const Controller = require('egg').Controller;
const utils = require('../utils');

class ChatController extends Controller {

  async getRoomList() {
    const { ctx } = this;
    const query = ctx.request.query;
    const user = ctx.request.user;

    const {
      pageNum, pageSize,
    } = query;

    const pageInfo = {
      pageNum: Number(pageNum), pageSize: Number(pageSize),
    };

    const option = {
      skip: (pageInfo.pageNum - 1) * pageInfo.pageSize,
      limit: pageInfo.pageSize || 10,
      sort: '-create_at',
    };

    const listQuery = {
      from_user_id: user.userId,
    };

    const totalCount = await ctx.service.chat.getChatRoomCountByQuery(listQuery);
    const [ list ] = await ctx.service.chat.getChatRoomList(listQuery, option);


    ctx.body = {
      success: true,
      pageList: list,
      page: {
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
        totalCount,
        pageTotalCount: utils.countTotalPageCount(totalCount, pageInfo.pageSize),
      },
    };
  }

  async getRoom() {
    const { ctx } = this;
    const query = ctx.request.query;
    const user = ctx.request.user;

    const {
      roomId,
    } = query;

    const [ chatRoom, fromUserData ] = await ctx.service.chat.getChatRoom(
      {
        roomId,
      }
    );

    await ctx.service.user.updateRoom({
      userId: user.userId,
      roomId,
    });

    ctx.body = {
      success: true,
      chatRoom,
      fromUserData,
    };
  }

  async getMessageList() {
    const { ctx } = this;
    const query = ctx.request.query;
    const user = ctx.request.user;
    
    const {
      roomId,
    } = query;

    let [ messageList ] = await ctx.service.chat.getMessageList(
      {
        roomId,
      }
    );

    if (messageList) {
      messageList = messageList.map(item => {
        if (item.from_user_id == user.userId) {
          item.self = true;
        }
        return item;
      });
    }

    ctx.body = {
      success: true,
      messageList,
    };
  }

  async getUserList() {
    const { ctx, app } = this;
    const users = Object.keys(app.ws.user || {});
    ctx.body = {
      success: true,
      users,
    };
  }

  async createChatRoom() {
    const { ctx } = this;
    const user = ctx.request.user;
    const {
      toUserId,
    } = body;
    
    const [ result ] = await ctx.service.chat.newChatRoom({
      fromUserId: user.userId,
      toUserId: toUserId,
    });

    ctx.body = {
      success: true,
      roomid: result._id,
    };
  }

  async send() {
    const { ctx, app } = this;
    const body = ctx.request.body;
    const user = ctx.request.user;

    const {
      roomId,
      toUserId,
      message,
    } = body;

    let close = false;

    const [ resultClose ] = await ctx.service.chat.incChatRommFromCount({
      fromUserId: user.userId,
      chatRoomId: roomId,
    });

    close = resultClose;
    
    if (close) {
      ctx.body = {
        success: true,
        close,
      }
      return;
    }

    const fromUser = {
      _id: user.userId,
    }
    console.log('from query: ', fromUser);
    
    
    const [ fromUserData ] = await ctx.service.user.getUser(fromUser);

    const toUser = {
      _id: toUserId,
    }
    
    console.log('fromUserData: ', fromUserData);

    const [ toUserData ] = await ctx.service.user.getUser(toUser);

    if (!toUserData) {
      const newToUser = new ctx.model.User();

      const osQuery = { chat_room_id: roomId };

      const os = await this.ctx.model.OrderSubscription.findOne(osQuery);

      const expertQuery = { _id: os.expert_id };
      
      const expertData = await this.ctx.model.Expert.findOne(expertQuery);

      newToUser.name = expertData.name;
      newToUser.avatar = expertData.avatar_image;

      let userSeq = await ctx.service.mongoCache.get('user_seq');
      userSeq = Number(userSeq || 0) + 1;

      await ctx.service.mongoCache.set('user_seq', userSeq);

      newToUser.code = utils.prefixInteger(userSeq, 6);

      toUserData = {
        _id: newToUser._id,
      };

      await newToUser.save();
    }

    const id = await ctx.service.chat.newChatMessage(
      toUserData, fromUserData, message, roomId
    );
    

    console.log('roomId', roomId);
    console.log('room_id', toUserData.room_id);
    
    if (app.ws.user &&
      app.ws.user[toUserId] &&
      toUserData.room_id === roomId) {
        
        console.log('send');

      app.ws.user[toUserId].send(JSON.stringify({
        msg: "receive",
        data: {
          roomId,
          message,
          create_at: new Date(),
          user,
        }
      }));
    }

    ctx.body = {
      success: true,
      close,
      id,
    }
  }

	// 连接socket
	async connect() {

    const { ctx, app, service } = this;
    
    ctx.websocket
      .on('connection', msg => {
        console.log('connection: ', msg);
      })
      .on('message', async (data) => {
        console.log('message: ', data);
        const userId = ctx.websocket.userId;
          
        if (data === 'HeartBeat') {
          ctx.websocket.send(JSON.stringify({ data }))
          return;
        }
        console.log('接收消息, data: %s, userId: %s', data, userId);

        const execData = JSON.parse(data);
        console.log('execData: ', execData);
        if (execData.msg === 'connected') {
          console.log('userId 登录成功 ', userId);
        }
			})
			.on('close', async (code, reason) => {
        
        // 用户下线
      
        let userId = ctx.websocket.userId;
        console.log('用户下线----',userId);
        // // 移除redis用户上线记录
        // // if(!app.ws.clearclear){
        //   console.log('remove_online_用户下线')
        //   //app.ws.clear = false
        //   service.cache.remove('online_' + user_id);

        //   if (app.ws.user && app.ws.user[user_id]) {
        //     delete app.ws.user[user_id];
        //   }
				// // }
				// // app.ws.clearclear = false
				// console.log('在线人数：',Object.keys(app.ws.user).length)
      });
      
  }
}

module.exports = ChatController;
